package com.tvunetworks.device.extra.resolver;

import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.device.extra.annotation.Logined;
import com.tvunetworks.device.extra.constants.ResultConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Etan Yang
 * @create: 2021/11/22 14:34
 */

public class LoginArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(Logined.class) != null
                && (parameter.getParameterType() == LoginUser.class
                || parameter.getParameterType() == String.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        String userId = request.getHeader("userid");
        if (StringUtils.isEmpty(userId)) {
            if (!StringUtils.containsIgnoreCase(request.getRequestURI(), "/base/") && !StringUtils.containsIgnoreCase(request.getRequestURI(), "/schedule/")) {
                throw new ServerException(ResultConstant.User.USER_ID_CAN_NOT_EMPTY);
            }
        }
        String email = request.getHeader("email");
        LoginUser loginUser = new LoginUser();
        loginUser.setId(userId);
        loginUser.setEmail(email);

        return loginUser;
    }
}
